<template>
  <div class="app-container">
    <div v-show="!purchAppDetailinfo.visible">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clearType="clearType"
          :slipSelectRequest="slipSelectRequest"
          ref="pageFilter"
        >
          <template v-slot:filter-createTime>
            <el-date-picker
              v-model="createTime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              :shortcuts="$fn.pickerOptionsFn()"
              align="right"
              start-placeholder="操作时间开始日期"
              end-placeholder="操作时间结束日期"
              :default-time="[
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 1, 1, 23, 59, 59),
              ]"
              @change="timeChange"
            ></el-date-picker>
          </template>
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-print>
            <el-button
              v-if="$permission('productPurchApplicationQuery:print')"
              @click="print"
              >打印</el-button
            >
          </template>
          <template v-slot:filter-excel>
            <el-button
              v-if="$permission('productPurchApplicationQuery:excel')"
              @click="exportExcel"
              >导出excel</el-button
            >
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <GroupSelect
            @callback="groupSelect"
            @callbackVal="updateGroupSelections"
            :options="groupSelectInfo.options"
            v-model:selections="groupSelectInfo.selections"
          ></GroupSelect>
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <TableContainer
        v-if="groupFlag"
        class="groupFlag-container"
        :isGroupSearch="true"
        v-model:data="groupSelectInfo.data"
        :field-list="tableInfo.fieldList"
        :checkBox="false"
        :tabIndex="false"
        :pager="false"
        :treeProps="{ children: 'children', hasChildren: 'hasChildren' }"
        @exChange="exChange"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
        :span-method="arraySpanMethod"
        :row-class-name="tableRowClassName"
      >
        <template v-slot:col-groupConcatApplicationOrderNo="scope">
          <span
            v-for="(item, index) in getOrderNo(
              scope.row.groupConcatApplicationOrderNoId
            )"
            :key="index"
            class="slip-edit"
            @click="showDetail(item)"
            >{{ index !== 0 ? ',' + item.orderNo : item.orderNo }}</span
          >
        </template>
      </TableContainer>
      <!-- 表格 -->
      <TableContainer
        v-else
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :summary="true"
        :summaryFieldList="tableInfo.summaryFieldList"
        :tab-index="true"
        :check-box="false"
        v-model:query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        @pageInfo="pageInfo"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-groupConcatApplicationOrderNo="scope">
          <span
            v-for="(item, index) in getOrderNo(
              scope.row.groupConcatApplicationOrderNoId
            )"
            :key="index"
            class="slip-edit"
            @click="showDetail(item)"
            >{{ index !== 0 ? ',' + item.orderNo : item.orderNo }}</span
          >
        </template>
      </TableContainer>
      <SetPreference
        v-if="preferenceInfo.visible"
        v-model:visible="preferenceInfo.visible"
        :searchList="filterInfo.searchList"
        :fieldList="tableInfo.fieldList"
        :customizeUserVO="filterInfo.query.customizeUserVO"
        @callback="setPreferenceCallback"
      />
      <AdvancedSearch
        v-if="advancedSearchInfo.visible"
        v-model:visible="advancedSearchInfo.visible"
        :fieldList="tableInfo.fieldList"
        v-model:formData="advancedSearchInfo.data"
        @callback="advancedSearchCallback"
      />
      <excelOrPrint :excelPrint="excelPrint"></excelOrPrint>
    </div>
    <PurchApplicationDetail
      v-if="purchAppDetailinfo.visible"
      v-model:visible="purchAppDetailinfo.visible"
      :table-row="purchAppDetailinfo.data"
      @returnBack="getList"
    />
  </div>
</template>

<script setup name="productPurchApplicationQuery">
import {
  exportProductPurchApplicationQueryRest,
  printProductPurchApplicationQueryRest,
  getProductPurchApplicationQueryRestCustomizeListPage,
  getProductPurchApplicationQueryRestCustomizeListAll,
  getProductPurchApplicationQueryRestCustomizeGroups,
} from '@/api/dataQuery.js'
import moment from 'moment'
const PurchApplicationDetail = defineAsyncComponent(() =>
  import('@/views/purch/application/detail')
)
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { ElMessage } from 'element-plus'
import { fatchTemplateByCode } from '@/api/base'
const { proxy } = getCurrentInstance()
const props = defineProps(['query'])
const clearType = ref(true)
const groupFlag = ref(false)
const slipSelectRequest = ref(true)
// 过滤相关配置
const groupSelectInfo = ref({
  options: [],
  selections: [],
  data: [],
})
const listTypeInfo = ref({
  typeList: [],
})
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      deptAuth: {
        asTbName: 'purch_application',
        columnName: 'dept_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'deptAuth',
      },
      createTime: {
        queryType: 'BETWEEN',
        value:
          moment(new Date(new Date().getTime() - 3600 * 1000 * 24 * 90)).format(
            'YYYY-MM-DD HH:mm:ss'
          ) +
          ',' +
          moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
      },
    },
    groupMap: {},
    groups: [],
    queryParams: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      value: 'print',
      type: 'slot',
    },
    {
      value: 'excel',
      type: 'slot',
    },
  ],
})
const createTime = ref([
  moment(new Date(new Date().getTime() - 3600 * 1000 * 24 * 90)).format(
    'YYYY-MM-DD HH:mm:ss'
  ),
  moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
])
const purchAppDetailinfo = ref({
  visible: false,
  title: '申购单明细',
  data: {},
})
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  summaryFieldList: [
    { value: 'statisticsAmount', formatter: proxy.$fn.qtyFormatter },
    {
      value: 'statisticsAmountOfMoney',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
  fieldList: [],
})
const detailListInfo = ref({
  visible: false,
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
function getOrderNo(orderNos) {
  if (!orderNos) {
    return
  }
  let arr = []
  orderNos.split(',').forEach((item) => {
    arr.push({
      orderNo: item.split('_')[0],
      id: item.split('_')[1],
    })
  })
  return arr
}
function showDetail(row) {
  purchAppDetailinfo.value.visible = true
  purchAppDetailinfo.value.data = { id: row.id, orderNo: row.orderNo }
}
function updateGroupSelections(arr) {
  filterInfo.value.query.groups = arr
  groupSelectInfo.value.selections = arr
  if (!arr.length) {
    filterInfo.value.query.groups = []
    filterInfo.value.query.groupMap = {}
    groupSelectInfo.value.data = []
    groupFlag.value = false
  }
}
function groupSelect(arr) {
  if (createTime.value) {
    let startTime =
      typeof createTime.value[0] === 'string'
        ? new Date(createTime.value[0])
        : createTime.value[0]
    let endTime =
      typeof createTime.value[1] === 'string'
        ? new Date(createTime.value[1])
        : createTime.value[1]
    if (endTime.getTime() - startTime.getTime() > 3600 * 1000 * 24 * 365) {
      proxy.$message.warning('操作时间间隔不能超过一年！')
    } else {
      if (arr.length) {
        //点击分组
        groupFlag.value = true
        filterInfo.value.query.groups = arr
        groupSelectInfo.value.selections = arr
        getCustomizeGroupsList()
      } else {
        ElMessage.warning({
          message: '请选择分组条件！',
          showClose: true,
          duration: 3000,
        })
      }
    }
  } else {
    proxy.$message.warning('请选择操作时间')
  }
}

async function getCustomizeGroupsList(len, param, expande) {
  //分组查询
  let params = {}
  if (len) {
    params = param
  } else {
    params = filterInfo.value.query
  }
  if (
    filterInfo.value.query.queryDtoList &&
    filterInfo.value.query.queryDtoList.length
  ) {
    params = proxy.$fn.deepClone(params)
    params.queryMap = {}
  }
  await getProductPurchApplicationQueryRestCustomizeGroups(params).then(
    async (res) => {
      if (res && res.success) {
        let data = res.data
        let newData = []
        if (len) {
          await data.forEach((item, index) => {
            newData.push({
              ...item,
              id: index + Math.random(),
              isColspan: true,
              children: [
                { ...item, id: index + Math.random(), isColspan: true },
              ],
            })
          })
          expande.children = newData
        } else {
          await data.forEach((item, index) => {
            newData.push({
              ...item,
              id: index + Math.random(),
              isColspan: true,
              children: [{ id: index + Math.random(), isColspan: true }],
            })
          })
          groupSelectInfo.value.data = newData
        }
      }
    }
  )
}
function exChange(data, expandedRows) {
  //展开分组
  if (expandedRows) {
    let len = data.nextGroups.length
    if (len) {
      let params = {
        ...filterInfo.value.query,
        groups: data.nextGroups,
        groupMap: { ...data.query },
        queryMap: { ...filterInfo.value.query.queryMap, ...data.query },
      }
      getCustomizeGroupsList(len, params, data)
    } else {
      let params = {
        ...filterInfo.value.query,
        groups: [],
        groupMap: {},
        queryMap: { ...filterInfo.value.query.queryMap, ...data.query },
      }
      getProductPurchApplicationQueryRestCustomizeListAll(params).then(
        async (res) => {
          if (res && res.success) {
            let resData = res.data
            await resData.forEach((item, index) => {
              item.id = index + Math.random()
              item.isColspan = false
            })
            data.children = resData
          }
        }
      )
    }
  } else {
    data.children = [{ id: Math.random(), isColspan: true }]
  }
}

function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {}
  let arr = [
    {
      asTbName: 'purch_application',
      columnName: 'dept_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'deptAuth',
    },
  ]
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  if ((await groupSelectInfo.value.selections.length) > 0) {
    await getCustomizeGroupsList()
  } else {
    groupSelectInfo.value.data = []
    await getList()
  }
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
async function getList() {
  tableInfo.value.refresh = Math.random()
}

function search() {
  if (createTime.value) {
    let startTime =
      typeof createTime.value[0] === 'string'
        ? new Date(createTime.value[0])
        : createTime.value[0]
    let endTime =
      typeof createTime.value[1] === 'string'
        ? new Date(createTime.value[1])
        : createTime.value[1]
    if (endTime.getTime() - startTime.getTime() > 3600 * 1000 * 24 * 365) {
      proxy.$message.warning('操作时间间隔不能超过一年！')
    } else {
      advancedSearchInfo.value.data = {}
      filterInfo.value.query.queryDtoList = []
      if (groupSelectInfo.value.selections.length > 0) {
        getCustomizeGroupsList()
      } else {
        groupSelectInfo.value.data = []
        tableInfo.value.initCurpage = Math.random()
        tableInfo.value.refresh = Math.random()
      }
    }
  } else {
    proxy.$message.warning('请选择操作时间')
  }
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )

  createTime.value = [
    moment(new Date(new Date().getTime() - 3600 * 1000 * 24 * 90)).format(
      'YYYY-MM-DD HH:mm:ss'
    ),
    moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
  ]
  filterInfo.value.query.queryMap.createTime.value =
    moment(new Date(new Date().getTime() - 3600 * 1000 * 24 * 90)).format(
      'YYYY-MM-DD HH:mm:ss'
    ) +
    ',' +
    moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'dataQueryProductPurchApplicationQuery-com.slip.spd.entity.vo.purch.PurchApplicationDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      let tableFieldInfo = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )

      tableInfo.value.fieldList = tableFieldInfo.fieldList
      groupSelectInfo.value.options = tableFieldInfo.groupOption
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      let queryIn = proxy.$route.params.query
      if (queryIn) {
        filterInfo.value.query.queryMap = {
          ...filterInfo.value.query.queryMap,
          ...queryIn.queryMap,
        }
        if (queryIn.queryMap.createTime) {
          createTime.value = queryIn.queryMap.createTime.value.split(',')
        }
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = getProductPurchApplicationQueryRestCustomizeListPage
      getList()
    }
  })
}

function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.toString()
    getList()
  }
}
function tableRowClassName(row) {
  if (row.row.nextGroups) {
    return 'bg-color-EBEEF5'
  } else {
    return ''
  }
}
function arraySpanMethod({ row, columnIndex }) {
  if (row.nextGroups) {
    if (columnIndex === 0) {
      return {
        rowspan: 1,
        colspan: tableInfo.value.fieldList.length,
      }
    }
  }
}
/* function exportExcel() {
  if (createTime.value) {
    let startTime =
      typeof createTime.value[0] === 'string'
        ? new Date(createTime.value[0])
        : createTime.value[0]
    let endTime =
      typeof createTime.value[1] === 'string'
        ? new Date(createTime.value[1])
        : createTime.value[1]
    if (endTime.getTime() - startTime.getTime() > 3600 * 1000 * 24 * 365) {
      proxy.$message.warning('操作时间间隔不能超过一年！')
    } else {
      exportProductPurchApplicationQueryRest(
        proxy.$fn.delEmptyAttribute(filterInfo.value.query)
      ).then((resp) => {
        if (resp) {
          proxy.$fn.parseExcel(resp)
        }
      })
    }
  } else {
    proxy.$message.warning('请选择操作时间')
  }
} */
function timeChange(val) {
  if (val && val.length) {
    filterInfo.value.query.queryMap.createTime.value = val[0] + ',' + val[1]
  } else {
    filterInfo.value.query.queryMap.createTime.value = null
  }
}
//打印
const excelPrint = ref({
  type: 'print', // 类型print/excel
  print: {
    fatchTemplateByCode: {
      // 获取打印模板参数
      resourceCode: 'productPurchApplicationQuery:print',
      isDefault: 1,
      $lodopPermission: true, // 是否有打印预览权限参数
    },
    api: printProductPurchApplicationQueryRest, // 打印数据接口
    params: {}, // 打印参数
  },
  excel: {
    api: exportProductPurchApplicationQueryRest, // 导出数据接口
    params: {}, // 导出参数
  },
  refresh: null,
})
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
//打印导出分页参数
function pageInfo(obj) {
  page.value = obj
}
//打印
function print() {
  excelPrint.value.type = 'print'
  excelPrint.value.print.params = proxy.$fn.deepClone({
    customizeDto: filterInfo.value.query,
    ...page.value,
  })
  excelPrint.value.refresh = Math.random()
}
//导出
function exportExcel() {
  excelPrint.value.type = 'excel'
  excelPrint.value.excel.params = proxy.$fn.deepClone({
    ...proxy.$fn.delEmptyAttribute(filterInfo.value.query),
    ...page.value,
  })
  excelPrint.value.refresh = Math.random()
}

/* function print() {
  if (createTime.value) {
    let startTime =
      typeof createTime.value[0] === 'string'
        ? new Date(createTime.value[0])
        : createTime.value[0]
    let endTime =
      typeof createTime.value[1] === 'string'
        ? new Date(createTime.value[1])
        : createTime.value[1]
    if (endTime.getTime() - startTime.getTime() > 3600 * 1000 * 24 * 365) {
      proxy.$message.warning('操作时间间隔不能超过一年！')
    } else {
      fatchTemplateByCode({
        resourceCode: 'productPurchApplicationQuery:print',
        isDefault: 1,
      }).then((res) => {
        if (res && res.success) {
          let temp = proxy.$fn.getPrintTemp(res.data[0])
          getPrintData(temp)
        }
      })
    }
  } else {
    proxy.$message.warning('请选择操作时间')
  }
}
function getPrintData(temp) {
  let params = {
    customizeDto: filterInfo.value.query,
  }
  printProductPurchApplicationQueryRest(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(
        temp,
        newData,
        !proxy.$permission('productPurchApplicationQuery:price')
      )
    }
  })
}
 */
let obj = {
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'purch_application_status_for_statistics',
    show: false,
    hidden: true,
  },
  price: {
    label: '单价',
    value: 'price',
    formatter: proxy.$fn.TripartiteMethod,
    type: 'column',
    componentType: 'price',
    permission: !proxy.$permission('productPurchApplicationQuery:price'),
    hidden: true,
    show: false,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    formatter: proxy.$fn.TripartiteMethod,
    type: 'column',
    componentType: 'price',
    permission: !proxy.$permission('productPurchApplicationQuery:price'),
    hidden: true,
    show: false,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    componentType: 'price',
    permission: !proxy.$permission('productPurchApplicationQuery:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
    show: false,
  },
  createTime: {
    label: '操作时间',
    value: 'createTime',
    componentType: 'dateTime',
    slot: true,
    show: false,
    hidden: true,
  },
  orderNo: {
    label: '单号',
    value: 'orderNo',
    componentType: 'input',
    show: false,
    type: 'column',
    hidden: true,
  },
  groupConcatApplicationUserName: {
    label: '申购人',
    value: 'groupConcatApplicationUserName',
    asValue: 'groupConcatApplicationUser',
    componentType: 'select-user',
    minWidth: '200px',
    highlightRow: true,
    checkBox: true,
    show: false,
    hidden: true,
  },
  groupConcatApplicationOrderNo: {
    label: '申购单号',
    value: 'groupConcatApplicationOrderNo',
    componentType: 'input',
    show: false,
    type: 'slot',
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
  commonName: {
    label: '通用名称',
    value: 'commonName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
})
getCustomize()
</script>

<style scoped></style>
